package cc.messcat.web.fupin;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.common.util.StringUtil;
import cc.messcat.entity.fupin.Family;
import cc.messcat.entity.fupin.VisitRecd;
import cc.messcat.entity.system.McUser;
import cc.messcat.log.OperationLog;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.VisitRecdService;
import cc.messcat.service.system.UserService;
import cc.messcat.web.filter.JsonFilter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.engine.transaction.jta.platform.internal.SynchronizationRegistryBasedSynchronizationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/visitRecd")
public class VisitRecdController {

	@Autowired
	private VisitRecdService visitRecdService;
	@Autowired
	public UserService userService;
	@Autowired
	public PoorFamilyService poorFamilyService;

	/**
	 * 查询帮扶记录列表
	 * @throws IOException 
	 */
//	@OperationLog(desc = "查询帮扶记录列表", module = "扶贫对象管理")
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/getVisitRecdPager", method = RequestMethod.POST)
	@ResponseBody
	public Object getVisitRecdPager(Integer pageNo, Integer pageSize, Long poorFaId, VisitRecd visitRecd,String beginDate,String endDate) throws IOException {
		pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
		pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

		
		Pager pager = this.visitRecdService.retrieveVisitRecdPager(pageNo, pageSize, visitRecd, beginDate, endDate);
	
		
		//数据处理
		getVisitRecdPagers(pager);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
	}

	

	/**
	 * 根据ID查询帮扶记录详情
	 * 
	 * @param id
	 * @return
	 * @throws IOException 
	 */
//	@OperationLog(desc = "根据ID查询帮扶记录详情", module = "扶贫对象管理")
	@RequestMapping(value = "/getVisitRecd", method = RequestMethod.POST)
	@ResponseBody
	public Object getVisitRecd(Long id) throws IOException {
		// VisitRecd visitRecd = this.visitRecdService.retrieveVisitRecd(id);
		VisitRecd visitRecd = this.visitRecdService.retrieveObject(id);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, new JsonFilter().jsonVisitRecdIdFilter(visitRecd));
	}

	/**
	 * 添加帮扶记录
	 */
	@OperationLog(desc = "添加帮扶记录", module = "扶贫对象管理")
	@RequestMapping(value = "/addVisitRecd", method = RequestMethod.POST)
	@ResponseBody
	public Object addVisitRecd(@Valid VisitRecd visitRecd, HttpSession session) {
		McUser mcUser = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		visitRecd.setIsDel("0");
		visitRecd.setAddtor(mcUser);
		visitRecd.setCreateTime(new Date());
		visitRecd.setAccTotal(StringUtil.isNotBlank(visitRecd.getAccessoryUrl())?String.valueOf(visitRecd.getAccessoryUrl().split(",").length):"0");
		Long id = visitRecdService.addVisitRecd(visitRecd);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS,id);
	}

	/**
	 * 编辑帮扶记录
	 */
	@OperationLog(desc = "编辑帮扶记录", module = "扶贫对象管理")
	@RequestMapping(value = "/editVisitRecd", method = RequestMethod.POST)
	@ResponseBody
	public Object editVisitRecd(@Valid VisitRecd visitRecd, HttpSession session) {
		VisitRecd visitRecd0 = this.visitRecdService.retrieveObject(visitRecd.getId());
	    if(visitRecd0!=null){
			McUser mcUser = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
			visitRecd0.setIsDel("0");
			visitRecd0.setUpTime(new Date());
			visitRecd0.setEdittor(mcUser);
			visitRecd0.setAddTime(visitRecd.getAddTime());
			visitRecd0.setTarget(visitRecd.getTarget());
			visitRecd0.setContent(visitRecd.getContent());
			visitRecd0.setRemarks(visitRecd.getRemarks());
			visitRecd0.setAccessoryUrl(visitRecd.getAccessoryUrl());
			visitRecd0.setAccTotal(StringUtil.isNotBlank(visitRecd.getAccessoryUrl())?String.valueOf(visitRecd.getAccessoryUrl().split(",").length):"0");
			this.visitRecdService.modifyObject(visitRecd0);
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS);
	    }
	    return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "数据不存在");

	}
	

    /**
     * 删除帮扶记录
     */
	@OperationLog(desc = "删除帮扶记录", module = "扶贫对象管理")
    @RequestMapping(value = "/deleteVisitRecd", method = RequestMethod.POST)
    @ResponseBody
	public Object deleteVisitRecd(Long id) {
		VisitRecd visitRecd = this.visitRecdService.retrieveObject(id);
		if (visitRecd != null) {
			visitRecd.setIsDel("1");
			this.visitRecdService.modifyObject(visitRecd);
		}
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS);
	}
    
    /**
	 * 导出帮扶记录
	 */
	@OperationLog(desc = "导出帮扶记录", module = "扶贫对象管理")
	@RequestMapping(value = "/exportVisitRecd")
	@ResponseBody
	public Object exportVisitRecd(Integer pageNo, Integer pageSize,@Valid VisitRecd visitRecd,HttpServletResponse response,String beginDate,String endDate) {
		
		pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
		pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;
		
		try {
			HSSFWorkbook wb = visitRecdService.exportVisitRecd(pageNo,pageSize,visitRecd,beginDate,endDate,response);
			
//			response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("帮扶记录","UTF-8")+".xls");
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
			wb.write(bufferedOutputStream);
			bufferedOutputStream.close();
			
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
		} catch (IOException e) {
			e.printStackTrace();
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
		}
	}
	
	
	/**
	 * 下载帮扶记录附件
	 * @param url
	 * @throws IOException 
	 */
	@OperationLog(desc = "下载帮扶记录附件", module = "扶贫对象管理")
	@RequestMapping("downloadAttachment")
	public void downloadVisitRecordAttachment(@RequestParam(name="url",required=true) String url,
		HttpServletResponse response,HttpSession session) throws IOException {
		if(StringUtils.isNotBlank(url)) {
			File attachment = new File(session.getServletContext().getRealPath("")+url);
			if(attachment.exists()) {
				response.setHeader("Content-Disposition",
					"attachment;filename=" + attachment.getName());
				response.setHeader("Pragma", "no-cache");
				response.setHeader("Cache-Control", "no-cache");
				FileUtils.copyFile(attachment, response.getOutputStream());
			}
		}
	}
	
	/**
	 * 查询帮扶记录列表数据处理
	 * @param pager
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void getVisitRecdPagers(Pager pager) {
		List<Object> list0 = new ArrayList<>();
		List<VisitRecd> list = pager.getResultList();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map=null;
			if (list.get(i) != null) {
				 map = new HashMap<>();
				map.put("id", list.get(i).getId());
				map.put("target", list.get(i).getTarget());
				map.put("content", list.get(i).getContent());
				map.put("faName", "");
				map.put("addTime", list.get(i).getAddTime() != null? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(i).getAddTime()) : "");
				for(Family f : list.get(i).getPoorFamily().getFamily()) {
					if("0".equals(f.getIsDel()) && "户主".equals(f.getRelation())) {
						map.put("faName", f.getName());
					}
				}
			}
			list0.add(map);
		}
		pager.setResultList(list0);
	}
	

}
